﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using PE_CE_PersonalINFO;
using System.Text.RegularExpressions;
using System.Drawing;
using AForge.Video;
using AForge.Video.DirectShow;
using System.Threading;
using System.Drawing.Imaging;
using WpfNavigationPane;
using System.Net;

namespace Abhiruchi_Phase1
{
    /// <summary>
    /// Interaction logic for HRM_EMPPersonal.xaml
    /// </summary>
    /// 
    #region Don't Touch me?
    public partial class UC_HRM_EMPPersonal : UserControl
    {
        //other variable
        public string ftpPathCheck;
        private static int rowCount4Docs = 0;
        string viewpath1, fnlpath;
        public static int cnt;
        private int reft = 0;
        //present
        string viewpathid, viewpathNA;
        string s = "";
        int Isactive;
        int cbSelect = 0;
        public String Eid;
        private string formtype;
        private string etype;
        public static string fnlPhotoup, fnlFPhotoup;

        //for captuure
        private FilterInfoCollection VideoCaptureDevices;
        private VideoCaptureDevice FinalVideo;

        //for testing
        public static List<TestCase> tstCaseObj = new List<TestCase>();

        private string empmode;
        private int flag = 0;
        public string IDProof, NTProof, OtherDoc1, Photo, FamilyPhoto, idproof, ntvproof;

        DataTable adt = new DataTable();
        //new paths
        public static List<filePaths> lstpaths = new List<filePaths>();
        public static List<filePaths> othersDocs = new List<filePaths>();
        public static List<filePaths> lstotherpaths = new List<filePaths>();

        //edit paths
        public static List<filePaths> lstDbPaths = new List<filePaths>();
        public static List<filePaths> lstRemovePaths = new List<filePaths>();
        public static List<filePaths> Updatedlst = new List<filePaths>();

        //documents collectios
        public static List<DocPaths> docDBPaths = new List<DocPaths>();//paths from DB
        public static List<DocPaths> docDBRemovePaths = new List<DocPaths>();//if remove db paths move that pathe this collection
        public static List<DocPaths> docDBUpdatePaths = new List<DocPaths>();//if upload in edit mode that path is taken to this collection

        //Collection To maintain other documents list
        Dictionary<int, string> DocDictionary = new Dictionary<int, string>();
        public static int clickCount = 0;
        //Fully Operation Perform and Validation

        public UC_HRM_EMPPersonal(string mode, string eid, string ftype)
        {
            InitializeComponent();

            initializeContentPersonal(mode, eid, ftype);

        }
        #region initialize content
        public void initializeContentPersonal(string mode, string eid, string ftype)
        {
            ClearFieldsPersonal();
            
            rowCount4Docs = 0;
            //clearing temp folder
            try
            {
                string tempPath = getPathofFile();
                tempPath += "\\" + "PersonalTemp";
                if (tempPath != null && tempPath != "")
                {
                    string[] filePaths = Directory.GetFiles(tempPath);
                    foreach (string filePath in filePaths)
                        File.Delete(filePath);
                }
            }
            catch (Exception ex)
            {
            }

            Eid = eid;
            formtype = ftype;

            if (mode == "Permanent Employee")
            {
                empmode = "Permanent";
                etype = "Permanent";
                lblOthers.Visibility = Visibility.Visible;
                txtDocName.Visibility = Visibility.Visible;
                Upload.Visibility = Visibility.Visible;
                scrollViewer1.Visibility = Visibility.Visible;
            }
            else if (mode == "Contract Employee")
            {
                empmode = "Contract";
                etype = "Contract";
                lblOthers.Visibility = Visibility.Collapsed;
                txtDocName.Visibility = Visibility.Collapsed;
                Upload.Visibility = Visibility.Collapsed;
                scrollViewer1.Visibility = Visibility.Collapsed;
            }
            ftpPathCheck = "ftp://118.139.163.181/" + "Documents" + "/" + "Employees" + "/" + empmode + "/" + eid + "/";
            chkIsActive.IsChecked = true;
            string path = getPathofFile();
            path += "\\Employees\\" + empmode + "\\FamilyPhoto.jpg";

            //MessageBox.Show(path);
            if (File.Exists(path))
            {
                btnUpLoadFamily.Content = Mode.ViewPhoto.ToString();//"View Photo";
                BitmapImage src = new BitmapImage();
                src.BeginInit();
                src.UriSource = new Uri(path.Trim(), UriKind.Relative);
                src.CacheOption = BitmapCacheOption.OnLoad;

                src.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                src.EndInit();
                imgFamilyPhoto.Source = src;

            }
            else
            {
                if (btnUpLoadFamily.Content.ToString() == Mode.Upload.ToString())//"Upload Photo")
                {
                    btnRemove.Visibility = Visibility.Collapsed;
                }
                else
                {
                    btnRemove.Visibility = Visibility.Visible;
                }

            }
            string photopath = getPathofFile();
            photopath += "\\Employees\\" + empmode + "\\" + Eid + "\\Photo.jpg";

            if (File.Exists(photopath))
            {
                btnUpload.Content = Mode.ViewPhoto.ToString(); //"View Photo";
                btnCapture.Content = Mode.Remove.ToString();//"Remove";
                BitmapImage src = new BitmapImage();
                src.BeginInit();
                src.UriSource = new Uri(photopath.Trim(), UriKind.Relative);
                src.CacheOption = BitmapCacheOption.OnLoad;

                src.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                src.EndInit();
                imgPhoto.Source = src;

            }
            else
            {
                btnCapture.Content = Mode.Capture.ToString();//"Capture";
                btnUpload.Content = Mode.Upload.ToString();//"Upload";
            }

            if (formtype == "NEW")
            {
                ViewIdProof.Visibility = Visibility.Collapsed;
                RemoveIdProof.Visibility = Visibility.Collapsed;
                btnViewNp.Visibility = Visibility.Collapsed;
                btnRemoveNp.Visibility = Visibility.Collapsed;               
                txtSpouseName.IsEnabled = false;
                scrollViewer1.Visibility = Visibility.Collapsed;
                EidAutogen();

            }
            if (formtype == "EDIT")
            {
                btnSave.Content = Mode.Upload.ToString();//"Update";
                FillControls();
            }

        }

        #endregion

        #region Auto Generation of EID to Every Form..

        public void EidAutogen()
        {
            DataTable dt = new DataTable();
            dt = PersonalInfoDAL.InsertdatatoEMPMaster(Eid, txtFirstName.Text + " " + txtFatherName.Text, etype, Isactive, flag);

            lblEID.Text = dt.Rows[0][0].ToString();

            Eid = lblEID.Text;
        }
        #endregion

        #region eid return
        public string eidReturn()
        {
            return Eid;
        }
        #endregion

        //Test automation
        //#region TEST for Automation...
        //private void btnTest_Click(object sender, RoutedEventArgs e)
        //{
        //    if (txtFirstName.Text == "")
        //    {
        //        MessageBox.Show("First Cannot be Empty");
        //        return;
        //    }
        //    if (rdoMale.IsChecked == false && rdoFemale.IsChecked == false)
        //    {
        //        MessageBox.Show("By defaulet Male is selected");
        //        return;
        //    }
        //    bool age = AgeCalculate();
        //    if (age == false)
        //    {
        //        MessageBox.Show("age less than 18");
        //        return;
        //    }
        //    if (txtFatherName.Text == "")
        //    {
        //        MessageBox.Show("Father name is Mandatory");
        //        return;
        //    }

        //}
        //#endregion

        #region Time for Fill the contrils on EDIT mode...
        //fillcontrols 
        public void FillControls()
        {
            if (lstDbPaths.Count > 0)
            {
                lstDbPaths.Clear();
            }
            int cntothers = 0;
            DataTable adt = new DataTable();
            adt = PersonalInfoDAL.GetPersonalInfoDB(Eid);
            //this table for documents
            DataTable docdt = new DataTable();
            docdt = PersonalInfoDAL.Get_PE_CE_Documents(Eid);

            DataTable IsAct = new DataTable();
            IsAct = PersonalInfoDAL.GetEmployeeMasterInfo(Eid);
            if (IsAct.Rows.Count > 0)
            {
                if (IsAct.Rows[0][5].ToString() == "1")
                {
                    chkIsActive.IsChecked = true;
                    SBar.Fill = System.Windows.Media.Brushes.Green;
                }
                else
                {
                    chkIsActive.IsChecked = false;
                    SBar.Fill = System.Windows.Media.Brushes.Red;
                }
            }

            if (adt.Rows.Count > 0)
            {
                lblEID.Text = adt.Rows[0][0].ToString();
                txtFirstName.Text = adt.Rows[0][1].ToString();
                txtLastName.Text = adt.Rows[0][2].ToString();
                if (adt.Rows[0][3].ToString().ToUpper() == "MALE")
                {
                    rdoMale.IsChecked = true;
                }
                else
                {
                    rdoFemale.IsChecked = true;
                }
                datePick.Text = adt.Rows[0][4].ToString();
                txtFatherName.Text = adt.Rows[0][5].ToString();
                cbMaritalStatus.Text = adt.Rows[0][6].ToString();
                txtSpouseName.Text = adt.Rows[0][7].ToString();

                string familyDbPath = adt.Rows[0][8].ToString();

               // if (File.Exists(familyDbPath))
                if(familyDbPath!="" && familyDbPath!=null)
                {
                    try
                    {
                        BitmapImage src = new BitmapImage();
                        src.BeginInit();
                        src.UriSource = new Uri(familyDbPath.Trim(), UriKind.Absolute);
                        src.CacheOption = BitmapCacheOption.OnLoad;

                        src.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                        src.EndInit();
                        imgFamilyPhoto.Source = src;
                        lstDbPaths.Add(new filePaths("FamilyPhoto", familyDbPath, "FamilyPhoto"));
                        //btnUpLoadFamily.Content = "View";
                        //btnRemove.Content = "Remove";
                        btnUpLoadFamily.Content = Mode.ViewPhoto.ToString();//"View Photo";
                        btnRemove.Visibility = Visibility.Visible;
                    }
                    catch (Exception ex) { }
                }
                else
                {
                    btnUpload.Content = Mode.ViewPhoto.ToString();//"View Photo";
                    btnCapture.Content = Mode.Remove.ToString();//"Remove";
                    btnUpLoadFamily.Content = Mode.Upload.ToString();//"Upload Photo";
                    btnRemove.Content = Mode.Remove.ToString();//"Remove";
                }
                string photoDbPath = adt.Rows[0][9].ToString();

              //  if (File.Exists(photoDbPath))
                if (photoDbPath != "" && photoDbPath != null)
                {
                    try
                    {
                        BitmapImage src = new BitmapImage();
                        src.BeginInit();
                        src.UriSource = new Uri(photoDbPath, UriKind.Absolute);
                        src.CacheOption = BitmapCacheOption.OnLoad;

                        src.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                        src.EndInit();
                        imgPhoto.Source = src;
                        lstDbPaths.Add(new filePaths("Photo", photoDbPath, "Photo"));
                        //Photo = photoDbPath;
                        btnUpload.Content = Mode.ViewPhoto.ToString();//"View Photo";
                        btnCapture.Content = Mode.Remove.ToString();// "Remove";
                    }
                    catch (Exception ex) { }
                }
                else
                {
                    btnUpload.Content = Mode.Upload.ToString();//"Upload";
                    btnCapture.Content = Mode.Capture.ToString();//"Capture";
                }
            }
            int docid = 0;
            string docName = "";
            string docPath = "";
            //string docType="";

            if (docdt.Rows.Count > 0)
            {
                for (int c = 0; c < docdt.Rows.Count; c++)
                {
                    docid = Int32.Parse(docdt.Rows[c][0].ToString());
                    docName = docdt.Rows[c][2].ToString();
                    docPath = docdt.Rows[c][3].ToString();
                    //docType
                    if (docName == "IDProof")
                    {
                        docDBPaths.Add(new DocPaths(docid, docName, docPath, "ID", ""));
                    }
                    else if (docName == "NativityProof")
                    {
                        docDBPaths.Add(new DocPaths(docid, docName, docPath, "NP", ""));
                    }
                    else
                    {
                        docDBPaths.Add(new DocPaths(docid, docName, docPath, "OTH", ""));
                    }


                }
            }

            for (int i = 0; i < docDBPaths.Count; i++)
            {
                if (docDBPaths[i].DOCTYPE == "ID")
                {
                    string[] x = docDBPaths[i].DOCPATH.Split('/');
                    lblIDNA.Text = SplitByLength(x[x.Length - 1], 20);

                }
                else if (docDBPaths[i].DOCTYPE == "NP")
                {
                    string[] x = docDBPaths[i].DOCPATH.Split('/');
                    lblNProofNA.Text = SplitByLength(x[x.Length - 1], 20);
                }
            }

            if (lblIDNA.Text == "")
            {
                UploadIDProof.Visibility = Visibility.Visible;
                ViewIdProof.Visibility = Visibility.Collapsed;
                RemoveIdProof.Visibility = Visibility.Collapsed;
            }
            else
            {
                UploadIDProof.Visibility = Visibility.Collapsed;
                ViewIdProof.Visibility = Visibility.Visible;
                RemoveIdProof.Visibility = Visibility.Visible;
            }

            if (lblNProofNA.Text == "")
            {
                btnUploadNp.Visibility = Visibility.Visible;
                btnViewNp.Visibility = Visibility.Collapsed;
                btnRemoveNp.Visibility = Visibility.Collapsed;
            }
            else
            {
                btnUploadNp.Visibility = Visibility.Collapsed;
                btnViewNp.Visibility = Visibility.Visible;
                btnRemoveNp.Visibility = Visibility.Visible;
            }


            for (int i = 0; i < lstDbPaths.Count; i++)
            {
                string[] s = lstDbPaths[i].FILENAME.Split('.');
                if (s[0] == "Photo" && s[0] == "FamilyPhoto" && s[0] == "IDProof" && s[0] == "NativityProof")
                {
                    cntothers++;
                }

            }
            Fillotherdocs();

        }
        #endregion

        #region AGE Calucation Depend on Calender Date
        //AGE Calucate
        private bool AgeCalculate()
        {
            DateTime today = DateTime.Now;
            DateTime Dob = (DateTime)datePick.SelectedDate;
            string age;
            age = ((today - Dob).Days).ToString();
            if (Int32.Parse(age) > 6570)
            {
                return true;
            }
            else
            {
                return false;
            }

        }
        #endregion

        String FileName;
        //File Upload
        private void btnUpload_Click(object sender, RoutedEventArgs e)
        {
            string path = getPathofFile();

            if (btnUpload.Content.ToString() == Mode.Upload.ToString())//"Upload")
            {
                #region new upload

                if (formtype == "NEW")
                {
                    path += "\\PersonalTemp";
                    photoUploadNEW(path);
                    //btnUpload.Content = Mode.ViewPhoto.ToString();
                }
                #endregion
                else
                {
                    path += "\\PersonalTemp";

                    OpenFileDialog fileDIalog = new OpenFileDialog();

                    fileDIalog.Filter = "All files (*.*)|*.*";

                    fileDIalog.AddExtension = true;

                    if (fileDIalog.ShowDialog() == true)
                    {
                        FileName = fileDIalog.FileName;
                        string newPath = path;
                        System.IO.Directory.CreateDirectory(newPath);
                        string[] spt = FileName.Split('\\');
                        string[] extension = spt[spt.Length - 1].Split('.');

                        path += "\\Photo" + "." + extension[extension.Length - 1];

                        Updatedlst.Add(new filePaths("Photo", path, "Photo"));

                        if (!File.Exists(path))
                        {
                            File.Copy(FileName, path);
                            BitmapImage src = new BitmapImage();
                            src.BeginInit();
                            src.UriSource = new Uri(path.Trim(), UriKind.Relative);
                            src.CacheOption = BitmapCacheOption.OnLoad;
                            src.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                            src.EndInit();
                            imgPhoto.Visibility = Visibility.Visible;
                            imgPhoto.Source = src;

                        }
                        else
                        {
                            BitmapImage src = new BitmapImage();
                            src.BeginInit();
                            src.UriSource = new Uri(path.Trim(), UriKind.Relative);
                            src.CacheOption = BitmapCacheOption.OnLoad;

                            src.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                            src.EndInit();
                            imgPhoto.Visibility = Visibility.Visible;
                            imgPhoto.Source = src;

                        }
                        btnCapture.Content = Mode.Remove.ToString();// "Remove";
                        btnUpload.Content = Mode.ViewPhoto.ToString();//"View Photo";
                    }

                }
            }
            else if (btnUpload.Content.ToString() == Mode.ViewPhoto.ToString())//"View Photo")
            {
                path += "\\PersonalTemp";
                path += "\\Photo.jpg";

                if (formtype == "NEW")
                {
                    for (int i = 0; i < lstpaths.Count; i++)
                    {
                        string[] s = lstpaths[i].FILENAME.Split('.');

                        if (s[0] == "Photo")
                        {
                            System.Diagnostics.Process.Start(lstpaths[i].FILEPATH);
                        }
                    }
                }
                else
                {

                    if (lstDbPaths.Count > 0)
                    {
                        for (int i = 0; i < lstDbPaths.Count; i++)
                        {
                            if (lstDbPaths[i].FILETYPE == "Photo")
                            {
                                System.Diagnostics.Process.Start(lstDbPaths[i].FILEPATH);
                            }
                        }
                    }
                    if (Updatedlst.Count > 0)
                    {
                        for (int i = 0; i < Updatedlst.Count; i++)
                        {
                            if (Updatedlst[i].FILETYPE == "Photo")
                            {
                                System.Diagnostics.Process.Start(Updatedlst[i].FILEPATH);
                            }
                        }
                    }




                }//EDIT closep


            }//view photo close


        }

        #region capture code
        void FinalVideo_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            //Thread.Sleep(50000);
            System.Drawing.Image imgforms = (Bitmap)eventArgs.Frame.Clone();

            BitmapImage bi = new BitmapImage();
            bi.BeginInit();

            MemoryStream ms = new MemoryStream();
            imgforms.Save(ms, ImageFormat.Bmp);
            ms.Seek(0, SeekOrigin.Begin);

            bi.StreamSource = ms;
            bi.EndInit();

            bi.Freeze();
            //Freezing the bitmapImage to avoid cross thread operation and then calling the UI thread using the Dispatcher to update the 'Image' WPF control called frameholder   

            Dispatcher.BeginInvoke(new ThreadStart(delegate
            {
                image1.Source = bi;
                if (reft == 0)
                {
                    btnCapture.Content = Mode.TakePhoto.ToString();//"Take Photo";
                }
                else
                {
                    btnCapture.Content = Mode.Remove.ToString();//"Remove";
                }

            }));

        }

        private void capture_Click(object sender, RoutedEventArgs e)
        {
            //to stop video pic will be in picbox1
            if (FinalVideo.IsRunning)
            {
                FinalVideo.Stop();
            }
        }

        private void save_Click(object sender, RoutedEventArgs e)
        {
            capture_Click(sender, e);
            SaveFrameToFile((BitmapSource)image1.Source);

        }
        private void SaveFrameToFile(BitmapSource source)
        {
            try
            {
                string photopath = getPathofFile();
                photopath += "\\PersonalTemp\\" + "Photo.jpg";
                FileStream stream = new FileStream(photopath, FileMode.Create);
                JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(source));
                encoder.Save(stream);
                stream.Close();
                if (formtype == "NEW")
                    lstpaths.Add(new filePaths("Photo", photopath, "Photo"));
                else
                    Updatedlst.Add(new filePaths("Photo", photopath, "Photo"));
            }
            catch (Exception e)
            {
                MessageBox.Show("Wait for Camera to laod", "Ooops!", MessageBoxButton.OK, MessageBoxImage.Asterisk);
            }

        }
        #endregion

        #region Capture Main Photo and Remove Photo
        private void btnCapture_Click(object sender, RoutedEventArgs e)
        {

            if (btnCapture.Content == Mode.Loading.ToString())//"Loading....")
            {
                return;
            }
            string path = getPathofFile();

            path += "\\PersonalTemp";

            if (btnCapture.Content.ToString() == Mode.Capture.ToString()) //"Capture")
            {
                try
                {
                    //capture code from moin
                    btnUpload.Visibility = Visibility.Hidden;
                    btnCapture.Content = Mode.Loading.ToString();//"Loading....";
                    VideoCaptureDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
                    for (int i = 0; i < 5; i++)
                    {
                        try
                        {
                            FinalVideo = new VideoCaptureDevice(VideoCaptureDevices[i].MonikerString);
                           // if (FinalVideo != null) break;
                        }
                        catch (Exception exc) { }
                    }
                    //FinalVideo.DesiredFrameSize = new Size(320, 240);
                    FinalVideo.DesiredFrameRate = 15;
                    FinalVideo.NewFrame += new NewFrameEventHandler(FinalVideo_NewFrame);
                    FinalVideo.Start();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Camera not Found", "Ooops!", MessageBoxButton.OK, MessageBoxImage.Warning);
                    btnCapture.Content = Mode.Capture.ToString();//"Capture";
                    btnUpload.Content = Mode.Upload.ToString();//"Upload";
                    btnUpload.Visibility = Visibility.Visible;
                }
            }
            else if (btnCapture.Content.ToString() == Mode.Remove.ToString())//"Remove")
            {
                if (image1.Source != null)
                {
                    image1.Source = null;
                    //if (File.Exists(path + "\\Photo.jpg"))
                    //    File.Delete(path + "\\Photo.jpg");
                    if (File.Exists(fnlPhotoup))
                        File.Delete(fnlPhotoup);
                    reft = 0;
                    for (int i = 0; i < lstpaths.Count; i++)
                    {
                        if (lstpaths[i].FILENAME == "Photo")
                        {
                            lstpaths.RemoveAt(i);
                        }
                    }
                }

                if (formtype == "NEW")
                {
                    path += "\\Photo.jpg";
                    if (File.Exists(fnlPhotoup))
                    {
                        File.Delete(fnlPhotoup);
                        for (int i = 0; i < lstpaths.Count; i++)
                        {
                            if (lstpaths[i].FILENAME == "Photo")
                            {
                                lstpaths.RemoveAt(i);
                            }
                        }
                        imgPhoto.Visibility = Visibility.Collapsed;
                    }
                }
                else
                {
                    if (lstDbPaths.Count > 0)
                    {
                        for (int i = 0; i < lstDbPaths.Count; i++)
                        {
                            if (lstDbPaths[i].FILETYPE == "Photo")
                            {
                                lstRemovePaths.Add(new filePaths(lstDbPaths[i].FILENAME, lstDbPaths[i].FILEPATH, "Photo"));
                                lstDbPaths.RemoveAt(i);
                            }
                        }
                    }
                    if (Updatedlst.Count > 0)
                    {

                        for (int i = 0; i < Updatedlst.Count; i++)
                        {
                            if (Updatedlst[i].FILETYPE == "Photo")
                            {
                                if (File.Exists(Updatedlst[i].FILEPATH))
                                {
                                    File.Delete(Updatedlst[i].FILEPATH);
                                }
                                Updatedlst.RemoveAt(i);
                            }
                        }
                    }
                    btnCapture.Content = Mode.Capture.ToString();//"Capture";
                    btnUpload.Content = Mode.Upload.ToString();//"Upload";
                    imgPhoto.Visibility = Visibility.Collapsed;


                }
                btnCapture.Content = Mode.Capture.ToString(); //"Capture";
                btnUpload.Content = Mode.Upload.ToString(); //"Upload";


                BitmapImage src = new BitmapImage();
                src.BeginInit();
                src.UriSource = new Uri(getPathofFile() + @"\Images\photoD.png", UriKind.Relative);
                src.CacheOption = BitmapCacheOption.OnLoad;
                src.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                src.EndInit();
                imgPhoto.Source = src;
                imgPhoto.Visibility = Visibility.Visible;
            }
            else if (btnCapture.Content.ToString() == Mode.TakePhoto.ToString())//"Take Photo")
            {
                reft = 1;
                save_Click(sender, e);
                btnUpload.Visibility = Visibility.Visible;
                btnUpload.Content = Mode.ViewPhoto.ToString();//"View Photo";
                btnCapture.Content = Mode.Remove.ToString();// "Remove";
            }
        }
        #endregion

        //File Removeppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp
        private void btnRemove_Click(object sender, RoutedEventArgs e)
        {
            string path = getPathofFile();

            path += "\\PersonalTemp";

            path += "\\FamilyPhoto.jpg";
            if (formtype == "NEW")
            {
                if (File.Exists(fnlFPhotoup))
                {
                    File.Delete(fnlFPhotoup);
                    for (int i = 0; i < lstpaths.Count; i++)
                    {
                        if (lstpaths[i].FILENAME == "FamilyPhoto")
                        {
                            lstpaths.RemoveAt(i);
                        }
                    }
                    imgFamilyPhoto.Visibility = Visibility.Collapsed;
                }
            }
            else
            {
                if (lstDbPaths.Count > 0)
                {
                    for (int i = 0; i < lstDbPaths.Count; i++)
                    {
                        if (lstDbPaths[i].FILETYPE == "FamilyPhoto")
                        {
                            lstRemovePaths.Add(new filePaths(lstDbPaths[i].FILENAME, lstDbPaths[i].FILEPATH, "FamilyPhoto"));
                            lstDbPaths.RemoveAt(i);
                        }
                    }
                }
                if (Updatedlst.Count > 0)
                {

                    for (int i = 0; i < Updatedlst.Count; i++)
                    {
                        if (Updatedlst[i].FILETYPE == "FamilyPhoto")
                        {
                            if (File.Exists(Updatedlst[i].FILEPATH))
                            {
                                File.Delete(Updatedlst[i].FILEPATH);
                            }
                            Updatedlst.RemoveAt(i);
                        }
                    }
                }
            }
            btnRemove.Visibility = Visibility.Collapsed;
            btnUpLoadFamily.Content = Mode.Upload.ToString();//"Upload Photo";
            //btnCapture.Content = "Capture";
            //btnUpload.Content = "Upload";
            BitmapImage src = new BitmapImage();
            src.BeginInit();
            src.UriSource = new Uri(getPathofFile() + @"\Images\family.png", UriKind.Relative);
            src.CacheOption = BitmapCacheOption.OnLoad;
            src.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            src.EndInit();
            imgFamilyPhoto.Source = src;
            imgFamilyPhoto.Visibility = Visibility.Visible;
        }

        //Get Photo
        private string getPathofFile()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory;
            string[] pathArray = path.Split(new char[] { '\\' });
            path = string.Empty;
            for (int temp = 0; temp < pathArray.Count() - 3; temp++)
            {
                if (temp == 0)
                    path = path + pathArray[temp];
                else
                    path = path + "\\" + pathArray[temp];
            }

            return path;
        }

        //Upload Family Photo
        private void btnUpLoadFamily_Click(object sender, RoutedEventArgs e)
        {
            btnRemove.Visibility = Visibility.Visible;
            String FileName;
            if (btnUpLoadFamily.Content.ToString() == Mode.Upload.ToString())//"Upload Photo")
            {
                string path = getPathofFile();
                if (formtype == "NEW")
                {
                    path += "\\PersonalTemp";
                    familyPhotoUploadNEW(path);

                }
                else
                {
                    path += "\\PersonalTemp";

                    OpenFileDialog fileDIalog = new OpenFileDialog();

                    fileDIalog.Filter = "All files (*.*)|*.*";

                    fileDIalog.AddExtension = true;

                    if (fileDIalog.ShowDialog() == true)
                    {
                        FileName = fileDIalog.FileName;
                        string newPath = path;
                        //System.IO.Directory.CreateDirectory(newPath);

                        string[] spt = FileName.Split('\\');
                        string[] extension = spt[spt.Length - 1].Split('.');

                        path += "\\FamilyPhoto" + "." + extension[extension.Length - 1];

                        Updatedlst.Add(new filePaths("FamilyPhoto", path, "FamilyPhoto"));

                        if (File.Exists(path))
                        {
                            File.Delete(path);
                        }
                        File.Copy(FileName, path);
                        BitmapImage src = new BitmapImage();
                        src.BeginInit();
                        src.UriSource = new Uri(path.Trim(), UriKind.Relative);
                        src.CacheOption = BitmapCacheOption.OnLoad;

                        src.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                        src.EndInit();
                        imgFamilyPhoto.Visibility = Visibility.Visible;
                        imgFamilyPhoto.Source = src;

                        btnRemove.Visibility = Visibility.Visible;
                        btnUpLoadFamily.Content = Mode.ViewPhoto.ToString();//"View Photo";

                    }
                }
                btnRemove.Visibility = Visibility.Visible;
                btnUpLoadFamily.Content = Mode.ViewPhoto.ToString();//"View Photo";
            }
            else
            {
                string path = getPathofFile();

                path += @"\PersonalTemp\FamilyPhoto.jpg";
                //MessageBox.Show(path);
                if (formtype == "NEW")
                {
                    System.Diagnostics.Process.Start(fnlPhotoup);
                }
                else
                {
                    if (lstDbPaths.Count > 0)
                    {
                        for (int i = 0; i < lstDbPaths.Count; i++)
                        {
                            if (lstDbPaths[i].FILETYPE == "FamilyPhoto")
                            {
                                System.Diagnostics.Process.Start(lstDbPaths[i].FILEPATH);
                            }
                        }
                    }
                    if (Updatedlst.Count > 0)
                    {
                        for (int i = 0; i < Updatedlst.Count; i++)
                        {
                            if (Updatedlst[i].FILETYPE == "FamilyPhoto")
                            {
                                System.Diagnostics.Process.Start(Updatedlst[i].FILEPATH);
                            }
                        }
                    }
                }



            }

        }

        #region Documents

        private void UploadIDProof_Click(object sender, RoutedEventArgs e)
        {
            if (formtype == "NEW")
            {
                string path = getPathofFile();

                path += "\\PersonalTemp";
                OpenFileDialog fileDIalog = new OpenFileDialog();
                fileDIalog.Filter = "All files (*.*)|*.*";
                fileDIalog.AddExtension = true;
                if (fileDIalog.ShowDialog() == true)
                {
                    String FileName = fileDIalog.FileName;
                    // string newPath = System.IO.Path.Combine(path, Eid);
                    System.IO.Directory.CreateDirectory(path);

                    String[] Docname;
                    Docname = FileName.Split('\\');
                    //lblview = Docname[Docname.Length - 1].ToString();
                    path += "\\" + Docname[Docname.Length - 1];
                    viewpathid = path;
                    if (File.Exists(path))
                    {
                        MessageBox.Show("Same file cannot be uploaded again", "Upload File", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                    if (!File.Exists(path))
                    {
                        File.Copy(FileName, path);
                        string[] s = Docname[Docname.Length - 1].Split('.');
                        lblIDNA.Text = SplitByLength(Docname[Docname.Length - 1], 20);
                        lstpaths.Add(new filePaths("IDProof", path, "ID"));
                        UploadIDProof.Visibility = Visibility.Collapsed;
                        ViewIdProof.Visibility = Visibility.Visible;
                        RemoveIdProof.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        MessageBox.Show("File is already Selected");
                        UploadIDProof.Visibility = Visibility.Visible;
                        ViewIdProof.Visibility = Visibility.Collapsed;
                        RemoveIdProof.Visibility = Visibility.Collapsed;
                    }
                }

            }
            else
            {
                string path = getPathofFile();
                path += "\\PersonalTemp";

                OpenFileDialog fileDIalog = new OpenFileDialog();

                fileDIalog.Filter = "All files (*.*)|*.*";

                fileDIalog.AddExtension = true;
                String FileName;
                if (fileDIalog.ShowDialog() == true)
                {
                    FileName = fileDIalog.FileName;
                    string newPath = path;
                    System.IO.Directory.CreateDirectory(newPath);

                    string[] spt = FileName.Split('\\');

                    path += "\\" + spt[spt.Length - 1];

                    if (File.Exists(path))
                    {
                        MessageBox.Show("Same file cannot be uploaded again", "Duplicate File", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    if (duplicateCheck(spt[spt.Length - 1]))
                    {
                        MessageBox.Show("Previously uploaded file cannot be uploaded again", "Uploaded File", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                    docDBUpdatePaths.Add(new DocPaths(1, "IDProof", path, "ID", ""));


                    lblIDNA.Text = SplitByLength(spt[spt.Length - 1], 20);

                    if (!File.Exists(path))
                    {
                        File.Copy(FileName, path);
                    }
                    else
                    {
                        //File.Delete(path);
                    }
                }
                UploadIDProof.Visibility = Visibility.Collapsed;
                ViewIdProof.Visibility = Visibility.Visible;
                RemoveIdProof.Visibility = Visibility.Visible;
            }
        }
        private void btnUploadNp_Click(object sender, RoutedEventArgs e)
        {
            if (formtype == "NEW")
            {
                String FileName;
                string path = getPathofFile();
                path += "\\PersonalTemp";
                OpenFileDialog fileDIalog = new OpenFileDialog();
                fileDIalog.Filter = "All files (*.*)|*.*";
                fileDIalog.AddExtension = true;
                if (fileDIalog.ShowDialog() == true)
                {
                    FileName = fileDIalog.FileName;
                    System.IO.Directory.CreateDirectory(path);
                    String[] Docname;
                    Docname = FileName.Split('\\');
                    path += "\\" + Docname[Docname.Length - 1];
                    viewpathNA = path;
                    if (File.Exists(path))
                    {
                        MessageBox.Show("Same file cannot be uploaded again", "File Upload", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                    if (duplicateCheck(Docname[Docname.Length - 1]))
                    {
                        MessageBox.Show("Previously uploaded file cannot be uploaded again", "Uploaded File", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    if (!File.Exists(path))
                    {
                        File.Copy(FileName, path);
                        lblNProofNA.Text = SplitByLength(Docname[Docname.Length - 1], 20);
                        string[] s = Docname[Docname.Length - 1].Split('.');
                        //lblNProofNA.Text = "NativityProof";
                        lstpaths.Add(new filePaths("NativityProof", path, "NP"));
                        btnUploadNp.Visibility = Visibility.Collapsed;
                        btnRemoveNp.Visibility = Visibility.Visible;
                        btnViewNp.Visibility = Visibility.Visible;

                    }
                    else
                    {
                        MessageBox.Show("File already Existed");
                        btnUploadNp.Visibility = Visibility.Visible;
                    }
                }

            }
            else
            {

                string path = getPathofFile();
                path += "\\PersonalTemp";

                OpenFileDialog fileDIalog = new OpenFileDialog();

                fileDIalog.Filter = "All files (*.*)|*.*";

                fileDIalog.AddExtension = true;
                String FileName;
                if (fileDIalog.ShowDialog() == true)
                {
                    FileName = fileDIalog.FileName;
                    string newPath = path;
                    System.IO.Directory.CreateDirectory(newPath);

                    string[] spt = FileName.Split('\\');

                    path += "\\" + spt[spt.Length - 1];
                    if (duplicateCheck(spt[spt.Length - 1]))
                    {
                        MessageBox.Show("Previously uploaded file cannot be uploaded again", "Verification", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    if (File.Exists(path))
                    {
                        MessageBox.Show("Same file cannot be uploaded again", "Duplicate File", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                    docDBUpdatePaths.Add(new DocPaths(1, "NativityProof", path, "NP", ""));

                    lblNProofNA.Text = SplitByLength(spt[spt.Length - 1], 20);
                    if (!File.Exists(path))
                    {
                        File.Copy(FileName, path);
                    }
                    else
                    {
                        //File.Delete(path);
                    }
                }
                btnUploadNp.Visibility = Visibility.Collapsed;
                btnRemoveNp.Visibility = Visibility.Visible;
                btnViewNp.Visibility = Visibility.Visible;

            }
        }
        #endregion

        //DuplicatesFile Check
        public bool duplicateCheck(string name)
        {
            string path =ftpPathCheck + name;

            for (int i = 0; i < docDBRemovePaths.Count; i++)
            {
                string[] splitPath = docDBRemovePaths[i].DOCPATH.Split('/');
                if (name == splitPath[splitPath.Length - 1])
                {
                    return false;
                }
            }

            if (CheckFTPFile(name, ftpPathCheck))
            {
                return true;
            }
            return false;
        }

        //ID Proof VIEW
        private void ViewIdProof_Click(object sender, RoutedEventArgs e)
        {
            if (formtype == "NEW")
            {
                System.Diagnostics.Process.Start(viewpathid);
            }
            else
            {
                string tempath = getPathofFile();

                if (docDBPaths.Count > 0)
                {
                    for (int i = 0; i < docDBPaths.Count; i++)
                    {
                        if (docDBPaths[i].DOCTYPE == "ID")
                        {
                           // tempath += "\\" + docDBPaths[i].DOCPATH;
                            try
                            {
                                System.Diagnostics.Process.Start(docDBPaths[i].DOCPATH);
                            }
                            catch (Exception ex) { }
                        }
                    }
                }

                if (docDBUpdatePaths.Count > 0)
                {
                    for (int i = 0; i < docDBUpdatePaths.Count; i++)
                    {
                        if (docDBUpdatePaths[i].DOCTYPE == "ID")
                        {
                            //tempath += "\\" + docDBUpdatePaths[i].DOCPATH;
                            try
                            {
                                System.Diagnostics.Process.Start(docDBUpdatePaths[i].DOCPATH);
                            }
                            catch (Exception ex) { }
                        }
                    }
                }

            }
        }

        //Nativite Proof
        private void btnViewNp_Click(object sender, RoutedEventArgs e)
        {
            if (formtype == "NEW")
            {
                System.Diagnostics.Process.Start(viewpathNA);
            }
            else
            {
                string tempath = getPathofFile();

                if (docDBPaths.Count > 0)
                {
                    for (int i = 0; i < docDBPaths.Count; i++)
                    {
                        if (docDBPaths[i].DOCTYPE == "NP")
                        {
                           // tempath += "\\" + docDBPaths[i].DOCPATH;
                            try
                            {
                                System.Diagnostics.Process.Start(docDBPaths[i].DOCPATH);
                            }
                            catch (Exception ex) { }
                        }
                    }
                }

                if (docDBUpdatePaths.Count > 0)
                {
                    for (int i = 0; i < docDBUpdatePaths.Count; i++)
                    {
                        if (docDBUpdatePaths[i].DOCTYPE == "NP")
                        {
                            //tempath += "\\" + docDBUpdatePaths[i].DOCPATH;
                            System.Diagnostics.Process.Start(docDBUpdatePaths[i].DOCPATH);
                        }
                    }
                }
            }
        }

        //REMOVE ID Proof
        private void RemoveIdProof_Click(object sender, RoutedEventArgs e)
        {
            if (formtype == "NEW")
            {
                File.Delete(viewpathid);

                for (int i = 0; i < lstpaths.Count; i++)
                {
                    if (lstpaths[i].FILETYPE == "ID")
                    {
                        File.Delete(lstpaths[i].FILEPATH);
                        lstpaths.RemoveAt(i);
                    }
                }
                lblIDNA.Text = "";
                ViewIdProof.Visibility = Visibility.Collapsed;
                RemoveIdProof.Visibility = Visibility.Collapsed;
                UploadIDProof.Visibility = Visibility.Visible;
            }
            else
            {

                if (docDBPaths.Count > 0)
                {
                    for (int i = 0; i < docDBPaths.Count; i++)
                    {
                        if (docDBPaths[i].DOCTYPE == "ID")
                        {
                            string path = getPathofFile();
                            path += "\\" + docDBPaths[i].DOCPATH;
                            //File.Delete(path);
                            docDBRemovePaths.Add(new DocPaths(docDBPaths[i].DOCID, docDBPaths[i].DOCNAME, docDBPaths[i].DOCPATH, "ID", ""));
                            docDBPaths.RemoveAt(i);
                        }
                    }
                }
                if (docDBUpdatePaths.Count > 0)
                {
                    for (int i = 0; i < docDBUpdatePaths.Count; i++)
                    {
                        if (docDBUpdatePaths[i].DOCTYPE == "ID")
                        {
                            //string path = getPathofFile();
                            //path += "\\" + docDBUpdatePaths[i].DOCPATH;
                            if (File.Exists(docDBUpdatePaths[i].DOCPATH))
                            {
                                File.Delete(docDBUpdatePaths[i].DOCPATH);
                            }
                            docDBUpdatePaths.RemoveAt(i);
                        }
                    }

                }

                UploadIDProof.Visibility = Visibility.Visible;
                ViewIdProof.Visibility = Visibility.Collapsed;
                RemoveIdProof.Visibility = Visibility.Collapsed;
                lblIDNA.Text = "";
            }
        }

        //Remove Nativite Proof
        private void btnRemoveNp_Click(object sender, RoutedEventArgs e)
        {
            if (formtype == "NEW")
            {
                for (int i = 0; i < lstpaths.Count; i++)
                {
                    if (lstpaths[i].FILETYPE == "NP")
                    {
                        File.Delete(viewpathNA);
                        lstpaths.RemoveAt(i);
                    }
                }
                btnViewNp.Visibility = Visibility.Collapsed;
                btnRemoveNp.Visibility = Visibility.Collapsed;
                btnUploadNp.Visibility = Visibility.Visible;

                lblNProofNA.Text = "";

            }
            else
            {

                if (docDBPaths.Count > 0)
                {
                    for (int i = 0; i < docDBPaths.Count; i++)
                    {
                        if (docDBPaths[i].DOCTYPE == "NP")
                        {
                            string path = getPathofFile();
                            path += "\\" + docDBPaths[i].DOCPATH;
                            //File.Delete(path);
                            docDBRemovePaths.Add(new DocPaths(docDBPaths[i].DOCID, docDBPaths[i].DOCNAME, docDBPaths[i].DOCPATH, "NP", ""));
                            docDBPaths.RemoveAt(i);
                        }
                    }
                }
                if (docDBUpdatePaths.Count > 0)
                {
                    for (int i = 0; i < docDBUpdatePaths.Count; i++)
                    {
                        if (docDBUpdatePaths[i].DOCTYPE == "NP")
                        {
                            //string path = getPathofFile();
                            // path += "\\" + docDBUpdatePaths[i].DOCPATH;
                            if (File.Exists(docDBUpdatePaths[i].DOCPATH))
                            {
                                File.Delete(docDBUpdatePaths[i].DOCPATH);
                            }
                            docDBUpdatePaths.RemoveAt(i);
                        }
                    }

                }
                lblNProofNA.Text = "";
                btnViewNp.Visibility = Visibility.Collapsed;
                btnRemoveNp.Visibility = Visibility.Collapsed;
                btnUploadNp.Visibility = Visibility.Visible;

            }
        }

        //Save Validation
        public void btnSave_Click(object sender, RoutedEventArgs e)
        {
            //if (!Validation())
            //{
            //    return;
            //}

            flag = 1;

            if (formtype == "NEW")
            {
                string ftpDir = "ftp://118.139.163.181/Documents/Employees/" + empmode + "/" + Eid;

                try
                {
                    WebRequest request = WebRequest.Create(ftpDir);
                    request.Method = WebRequestMethods.Ftp.MakeDirectory;
                    WebResponse response = request.GetResponse();
                }
                catch (Exception ex)
                {
                }
                finally
                {

                    Newform();
                    //clearing temp folder
                   
                }
                //MessageBox.Show("Employee Data is Successfully Saved", "Data Saving...", MessageBoxButton.OK, MessageBoxImage.Information);
            }

            else if (formtype == "EDIT")
            {
                // FillControls();
                Editform();
                //clearing temp folder
                //string tempPath = getPathofFile();
                //tempPath += "\\" + "PersonalTemp";
                //if (tempPath != null && tempPath != "")
                //{
                //    string[] filePaths = Directory.GetFiles(tempPath);
                //    foreach (string filePath in filePaths)
                //        File.Delete(filePath);
                //}
                // MessageBox.Show("Employee Data is Successfully Updated", "Data Updating", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            // btnSave.Content = "Saved";
            ClearFieldsPersonal();
        }

        private void chkIsActive_Click(object sender, RoutedEventArgs e)
        {
            if (chkIsActive.IsChecked == true)
            {
                SBar.Fill = System.Windows.Media.Brushes.Green;
            }
            else
            {
                SBar.Fill = System.Windows.Media.Brushes.Red;
            }
        }

        private void chkIsActive_MouseMove(object sender, MouseEventArgs e)
        {

        }

        //If Form Mode is NEW then Perform Folowing Operations
        public void Newform()
        {
            string s; int Isactive;
            DataTable mydt = new DataTable();
            if (rdoFemale.IsChecked == true)
            {
                s = rdoFemale.Content.ToString();
            }
            else
            {
                s = rdoMale.Content.ToString();
            }
            if (chkIsActive.IsChecked == true)
            {
                Isactive = 1;
            }
            else
            {
                Isactive = 0;

            }
            ucDocs oobj = new ucDocs();
            //append code from koti


            //string path = getPathofFile();
            string ftpPath = "ftp://118.139.163.181/" + "Documents" + "/" + "Employees" + "/" + empmode + "/" + Eid + "/";
            
            
            for (int i = 0; i < lstpaths.Count; i++)
            {
                if (lstpaths[i].FILENAME == "Photo")
                {
                    Photo = ftpPath + "Photo.jpg";
                    if (File.Exists(ftpPath)) File.Delete(Photo);

                    try
                    {
                        using (WebClient webClient = new WebClient())
                        {
                            webClient.UploadFile(Photo, lstpaths[i].FILEPATH);
                        }
                    }
                    catch (Exception ex) { }
                    //File.Delete(lstpaths[i].FILEPATH);
                    lstpaths[i].FILENAME = "Photo";
                    lstpaths[i].FILEPATH = Photo;

                    //Photo = lstpaths[i].FILEPATH;
                    //Photo = ftpPath;
                    //MessageBox.Show(lstpaths[i].FILEPATH);

                }
            }


            

            for (int i = 0; i < lstpaths.Count; i++)
            {
                if (lstpaths[i].FILENAME == "FamilyPhoto")
                {
                    FamilyPhoto = ftpPath + "FamilyPhoto.jpg";
                    if (File.Exists(FamilyPhoto)) File.Delete(FamilyPhoto);

                    try
                    {
                        using (WebClient webClient = new WebClient())
                        {
                            webClient.UploadFile(FamilyPhoto, lstpaths[i].FILEPATH);
                        }
                    }
                    catch (Exception ex) { }
                    lstpaths[i].FILENAME = "FamilyPhoto";
                    lstpaths[i].FILEPATH = FamilyPhoto;

                    //FamilyPhoto = "Documents\\Employees\\" + empmode + "\\" + Eid + "\\FamilyPhoto.jpg";//lstpaths[i].FILEPATH;
                    //MessageBox.Show(lstpaths[i].FILEPATH);
                }
            }

            //conditions for documents upload

            string identity=ftpPath;
            for (int i = 0; i < lstpaths.Count; i++)
            {
                if (lstpaths[i].FILETYPE == "ID")
                {
                    string[] splitpath = lstpaths[i].FILEPATH.Split('\\');


                    identity += splitpath[splitpath.Length - 1];//lstpaths[i].FILENAME;

                    if (File.Exists(identity)) File.Delete(identity);
                    try
                    {
                        using (WebClient webClient = new WebClient())
                        {
                            webClient.UploadFile(identity, lstpaths[i].FILEPATH);
                        }
                    }
                    catch (Exception ex) { }
                    lstpaths[i].FILENAME = lblIDNA.Text;
                    lstpaths[i].FILEPATH = identity;
                    idproof = lstpaths[i].FILEPATH;
                    lstotherpaths.Add(new filePaths("IDProof", identity, "ID"));
                    //MessageBox.Show(lstpaths[i].FILEPATH);

                }
            }


            string nativity = ftpPath;

            for (int i = 0; i < lstpaths.Count; i++)
            {
                if (lstpaths[i].FILETYPE == "NP")
                {
                    string[] splitpath = lstpaths[i].FILEPATH.Split('\\');


                    nativity += splitpath[splitpath.Length - 1];
                    //nativity += lstpaths[i].FILENAME;
                    if (File.Exists(nativity)) File.Delete(nativity);
                    try
                    {
                        using (WebClient webClient = new WebClient())
                        {
                            webClient.UploadFile(nativity, lstpaths[i].FILEPATH);
                        }
                    }
                    catch (Exception ex) { }
                    lstpaths[i].FILENAME = lblNProofNA.Text;
                    lstpaths[i].FILEPATH = nativity;
                    ntvproof = lstpaths[i].FILEPATH;
                    lstotherpaths.Add(new filePaths("NativityProof", ntvproof, "NP"));
                    //MessageBox.Show(lstpaths[i].FILEPATH);

                }
            }
            //Other Documents move to Permanent



            for (int i = 0; i < lstpaths.Count; i++)
            {
                if (lstpaths[i].FILETYPE == "OTF")// != "Photo" && lstpaths[i].FILENAME != "FamilyPhoto")//&& lstpaths[i].FILENAME != lblNProofNA.Text && lstpaths[i].FILENAME != lblIDNA.Text)
                {
                    string otherpat = ftpPath + "/";


                    string[] docsp = lstpaths[i].FILENAME.Split('|');
                    otherpat += docsp[0];
                   // if (File.Exists(otherpat)) File.Delete(otherpat);
                   // File.Copy(lstpaths[i].FILEPATH, otherpat);
                    try
                    {
                        using (WebClient webClient = new WebClient())
                        {
                            webClient.UploadFile(otherpat, lstpaths[i].FILEPATH);
                        }
                    }catch(Exception ex){}

                    // }
                    lstotherpaths.Add(new filePaths(lstpaths[i].FILENAME, otherpat, "OTF"));
                    otherpat = "";

                }

            }
            mydt = PersonalInfoDAL.InsertdatatoEMPMaster(Eid, txtFirstName.Text + " " + txtLastName.Text, etype, Isactive, flag);
            mydt = PersonalInfoDAL.InsertDataintoDB(Eid, txtFirstName.Text, txtLastName.Text, s, datePick.Text, txtFatherName.Text, cbMaritalStatus.Text, txtSpouseName.Text, Photo, FamilyPhoto);


            //lblEID.Text = mydt.Rows[0][0].ToString();

            for (int count = 0; count < lstotherpaths.Count; count++)
            {
              //  string[] storepath = lstotherpaths[count].FILEPATH.Split('\\');
                string str = lstotherpaths[count].FILEPATH;
                if (lstotherpaths[count].FILENAME != "IDProof" && lstotherpaths[count].FILENAME != "NativityProof")
                {
                    if (lstotherpaths[count].FILETYPE == "OTF")
                    {
                        string[] docn = lstotherpaths[count].FILENAME.Split('|');
                        PersonalInfoDAL.InsertDocstoDB(Eid, docn[1], str);
                    }
                }
                else
                {
                    PersonalInfoDAL.InsertDocstoDB(Eid, lstotherpaths[count].FILENAME, str);
                }
            }

        }

        //If Form Mode is EDIT then Perform follwong operations
        public void Editform()
        {
            DataTable mydt = new DataTable();
            if (rdoFemale.IsChecked == true)
            {
                s = rdoFemale.Content.ToString();
            }
            else
            {
                s = rdoMale.Content.ToString();
            }
            if (chkIsActive.IsChecked == true)
            {
                Isactive = 1;
            }
            else
            {
                Isactive = 0;
            }

            if (lstDbPaths.Count > 0)
            {
                for (int i = 0; i < lstDbPaths.Count; i++)
                {
                    if (lstDbPaths[i].FILETYPE == "Photo")
                    {
                        Photo = lstDbPaths[i].FILEPATH;
                    }
                    else if (lstDbPaths[i].FILETYPE == "FamilyPhoto")
                    {
                        FamilyPhoto = lstDbPaths[i].FILEPATH;
                    }
                }
            }

            if (Updatedlst.Count > 0)
            {

                for (int i = 0; i < Updatedlst.Count; i++)
                {
                    if (Updatedlst[i].FILETYPE == "Photo")
                    {
                        string path = "";
                        ////string fnlpath = getPathofFile();
                        //string fnlpath = @"ftp://118.139.163.181/photo2.jpg";
                        //string[] spt = Updatedlst[i].FILEPATH.Split('\\');
                        ////fnlpath +=   "Documents" + "//" + "Employees" + "//" + empmode + "//" + Eid + "//" + spt[spt.Length - 1];
                        ////if (File.Exists(fnlpath)) File.Delete(fnlpath);
                        //File.Copy(Updatedlst[i].FILEPATH, fnlpath);
                        //Photo = "Documents" + "\\" + "Employees" + "\\" + empmode + "\\" + Eid + "\\" + spt[spt.Length - 1];

                        

                        string[] spt = Updatedlst[i].FILEPATH.Split('\\');
                         path =  "ftp://118.139.163.181/" + "Documents" + "/" + "Employees" + "/" + empmode + "/" + Eid + "/" + spt[spt.Length - 1];
                         try
                         {
                             using (WebClient webClient = new WebClient())
                             {
                                 webClient.UploadFile(path, Updatedlst[i].FILEPATH);
                             }
                             Photo = path;
                         }
                         catch (Exception ex) { }


                    }
                    else if (Updatedlst[i].FILETYPE == "FamilyPhoto")
                    {
                        //string fnlpath = getPathofFile();
                        //string[] spt = Updatedlst[i].FILEPATH.Split('\\');
                        //fnlpath += "\\" + "Documents" + "\\" + "Employees" + "\\" + empmode + "\\" + Eid + "\\" + spt[spt.Length - 1];
                        //if (File.Exists(fnlpath)) File.Delete(fnlpath);
                        //File.Copy(Updatedlst[i].FILEPATH, fnlpath);
                        //FamilyPhoto = "Documents" + "\\" + "Employees" + "\\" + empmode + "\\" + Eid + "\\" + spt[spt.Length - 1];

                        string[] spt = Updatedlst[i].FILEPATH.Split('\\');
                        string path = "ftp://118.139.163.181/" + "Documents" + "/" + "Employees" + "/" + empmode + "/" + Eid + "/" + spt[spt.Length - 1];
                        try
                        {
                            using (WebClient webClient = new WebClient())
                            {
                                webClient.UploadFile(path, Updatedlst[i].FILEPATH);
                            }
                            FamilyPhoto = path;
                        }
                        catch (Exception ex) { }

                    }
                }
            }
            try
            {
                if (Photo == null && Photo == "")
                {
                    string photopath = "ftp://118.139.163.181/" + "Documents" + "/" + "Employees" + "/" + empmode + "/" + Eid + "/" + "Photo.jpg";

                    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(photopath);
                    request.Method = WebRequestMethods.Ftp.DeleteFile;

                    FtpWebResponse response = (FtpWebResponse)request.GetResponse();


                    response.Close();
                }
            }
            catch (Exception e)
            { }
            try
            {
                if (FamilyPhoto == null && FamilyPhoto == "")
                {
                    string photopath = "ftp://118.139.163.181/" + "Documents" + "/" + "Employees" + "/" + empmode + "/" + Eid + "/" + "FamilyPhoto.jpg";


                    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(photopath);
                    request.Method = WebRequestMethods.Ftp.DeleteFile;

                    FtpWebResponse response = (FtpWebResponse)request.GetResponse();


                    response.Close();
                }
            }catch(Exception ex)
                {}

            PersonalInfoDAL.UpdateEMPMaster(Eid, txtFirstName.Text + " " + txtLastName.Text, etype, Isactive);
            PersonalInfoDAL.UpdatePersonalInfotoDB(lblEID.Text, txtFirstName.Text, txtLastName.Text, s, datePick.Text, txtFatherName.Text, cbMaritalStatus.Text, txtSpouseName.Text, Photo, FamilyPhoto);

            if (docDBRemovePaths.Count > 0)
            {
                for (int i = 0; i < docDBRemovePaths.Count; i++)
                {
                    if (docDBRemovePaths[i].DOCTYPE == "Documents")
                    {
                        try
                        {
                            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(docDBRemovePaths[i].DOCPATH);
                            request.Method = WebRequestMethods.Ftp.DeleteFile;

                            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                            PersonalInfoDAL.DeleteDocumentsfromDB(Eid, docDBRemovePaths[i].DOCID);
                            // docDBRemovePaths.RemoveAt(i);
                        }
                        catch (Exception ex) { }
                    }
                    else
                    {
                        try
                        {
                            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(docDBRemovePaths[i].DOCPATH);
                            request.Method = WebRequestMethods.Ftp.DeleteFile;

                            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                            PersonalInfoDAL.DeleteDocumentsfromDB(Eid, docDBRemovePaths[i].DOCID);
                            //docDBRemovePaths.RemoveAt(i);
                        }
                        catch (Exception ex) { }
                    }
                }
            }
            for (int i = 0; i < docDBUpdatePaths.Count; i++)
            {
                string[] spt = docDBUpdatePaths[i].DOCPATH.Split('\\');
                string ftpPath = "ftp://118.139.163.181/" + "Documents" + "/" + "Employees" + "/" + empmode + "/" + Eid + "/" + spt[spt.Length - 1];
                try
                {
                    using (WebClient webClient = new WebClient())
                    {
                        webClient.UploadFile(ftpPath, docDBUpdatePaths[i].DOCPATH);
                    }
                }
                catch (Exception ex) { }
                PersonalInfoDAL.InsertDocstoDB(Eid, docDBUpdatePaths[i].DOCNAME, ftpPath);

            }
            for (int i = 0; i < lstRemovePaths.Count; i++)
            {
                string[] spt = lstRemovePaths[i].FILEPATH.Split('\\');
                if (spt[0] == "Documents")
                {
                    if (lstRemovePaths[i].FILENAME != "Photo" && lstRemovePaths[i].FILENAME != "FamilyPhoto")
                    {
                        string ftpPath = "ftp://118.139.163.181/" + "Documents" + "/" + "Employees" + "/" + empmode + "/" + Eid + "/" + spt[spt.Length - 1];
                        try
                        {
                            using (WebClient webClient = new WebClient())
                            {
                                webClient.UploadFile(ftpPath, Updatedlst[i].FILEPATH);
                            }
                        }
                        catch (Exception ex) { }
                        lstRemovePaths.RemoveAt(i);
                    }
                }
                else
                {
                    if (lstRemovePaths[i].FILENAME != "Photo" && lstRemovePaths[i].FILENAME != "FamilyPhoto")
                    {
                        File.Delete(lstRemovePaths[i].FILEPATH);
                        lstRemovePaths.RemoveAt(i);
                    }
                }

            }
        }

        #region other documents

        private void Upload_Click(object sender, RoutedEventArgs e)
        {
            if (txtDocName.Text == null || txtDocName.Text == "" || txtDocName.Text == "Document Name")
            {
                MessageBox.Show("Provide a Proper Name For Document");
                return;
            }

            if (formtype == "NEW")
            {
                scrollViewer1.Visibility = Visibility.Visible;
                string FileName;
                String temppath = "PersonalTemp";
                string path = getPathofFile();

                path += "\\PersonalTemp\\";
                //MessageBox.Show(path);
                OpenFileDialog fileDIalog = new OpenFileDialog();
                fileDIalog.Filter = "All files (*.*)|*.*";
                fileDIalog.AddExtension = true;
                if (fileDIalog.ShowDialog() == true)
                {
                    FileName = fileDIalog.FileName;
                    string newPath = System.IO.Path.Combine(path, temppath);
                    System.IO.Directory.CreateDirectory(path);//Path = Directory of files to be copied to Project folder
                    String[] fileName;

                    fileName = FileName.Split('\\');
                    path += fileName[fileName.Length - 1];

                    // lstCompareNames.Add(new filePaths(fileName[fileName.Length - 1],"ID"));
                    //path += "\\" + txtDocName.Text + "." + srcpath[1];//fileName[fileName.Length - 1];
                    viewpath1 = path;

                    if (File.Exists(path))
                    {
                        MessageBox.Show("Same file cannot be uploaded again", "Dulpicate File", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    if (!File.Exists(path))
                    {
                        File.Copy(FileName, path);
                        RowDefinition rd = new RowDefinition();
                        rd.Name = "row1";
                        grdDocs.RowDefinitions.Add(rd);
                        ucDocs ucObj = new ucDocs();
                        Grid.SetRow(ucObj, rowCount4Docs++);

                        string[] str = viewpath1.Split('\\');
                        string destpath = str[str.Length - 1]; //Split Destination file
                        string namev = cnt + "view";
                        string namer = cnt + "remove";
                        string namel = cnt + "label";

                        ucObj.Uid = cnt + "uc";
                        ucObj.btnDocView.Uid = namev;
                        ucObj.btnDocRemove.Uid = namer;
                        ucObj.lblDocName.Uid = namel;
                        cnt++;
                        ucObj.lblDocName.Content = txtDocName.Text;
                        ucObj.lblFname.Content = SplitByLength(str[str.Length - 1], 20);

                        fnlpath = path;
                        DocDictionary.Add(cnt, txtDocName.Text);
                        ucObj.btnDocView.Click += new RoutedEventHandler(btnDocView_Click);
                        ucObj.btnDocRemove.Click += new RoutedEventHandler(btnDocRemove_Click);
                        grdDocs.Children.Add(ucObj);
                        lstpaths.Add(new filePaths(fileName[fileName.Length - 1] + "|" + txtDocName.Text + "|" + namel, path, "OTF"));
                    }
                    else
                    {
                        MessageBox.Show("File already selected");
                    }
                }
                txtDocName.Text = "";
            }
            else
            {
                string FileName;
                String temppath = "PersonalTemp";
                string path = getPathofFile();
                scrollViewer1.Visibility = Visibility.Visible;
                path += "\\PersonalTemp\\";
                //MessageBox.Show(path);
                OpenFileDialog fileDIalog = new OpenFileDialog();
                fileDIalog.Filter = "All files (*.*)|*.*";
                fileDIalog.AddExtension = true;
                if (fileDIalog.ShowDialog() == true)
                {
                    FileName = fileDIalog.FileName;
                    string newPath = System.IO.Path.Combine(path, temppath);
                    System.IO.Directory.CreateDirectory(path);//Path = Directory of files to be copied to Project folder
                    String[] fileName;

                    fileName = FileName.Split('\\');
                    path += fileName[fileName.Length - 1];

                    // lstCompareNames.Add(new filePaths(fileName[fileName.Length - 1],"ID"));
                    //path += "\\" + txtDocName.Text + "." + srcpath[1];//fileName[fileName.Length - 1];
                    viewpath1 = path;

                    if (File.Exists(path))
                    {
                        MessageBox.Show("Same file cannot be uploaded again", "Duplicate File", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                    if (duplicateCheck(fileName[fileName.Length - 1]))
                    {
                        MessageBox.Show("Previously uploaded file cannot be uploaded again", "Verification", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    if (!File.Exists(path))
                    {
                        File.Copy(FileName, path);
                    }
                    else
                    {
                        MessageBox.Show("File already selected");
                    }
                    //othersDocs.Add(new filePaths(fileName[fileName.Length - 1], path,"OTF"));
                    //string[] s = (fileName[fileName.Length - 1].ToString()).Split('.');
                    RowDefinition rd = new RowDefinition();
                    rd.Name = "row1";
                    grdDocs.RowDefinitions.Add(rd);
                    ucDocs ucObj = new ucDocs();
                    Grid.SetRow(ucObj, rowCount4Docs++);

                    string[] str = viewpath1.Split('\\');
                    string destpath = str[str.Length - 1]; //Split Destination file
                    string namev = cnt + "view";
                    string namer = cnt + "remove";
                    string namel = cnt + "label";
                    ucObj.Uid = cnt + "uc";
                    cnt++;
                    ucObj.btnDocView.Uid = namev;
                    ucObj.btnDocRemove.Uid = namer;
                    ucObj.lblDocName.Uid = namel;

                    ucObj.lblDocName.Content = txtDocName.Text;

                    ucObj.lblFname.Content = SplitByLength(str[str.Length - 1], 20);


                    fnlpath = path;
                    DocDictionary.Add(cnt, txtDocName.Text);
                    ucObj.btnDocView.Click += new RoutedEventHandler(btnDocView_Click);
                    ucObj.btnDocRemove.Click += new RoutedEventHandler(btnDocRemove_Click);
                    grdDocs.UpdateLayout();
                    grdDocs.Children.Add(ucObj);
                    docDBUpdatePaths.Add(new DocPaths(1, txtDocName.Text, fnlpath, "OTH", (cnt - 1).ToString()));

                }
            }
            txtDocName.Text = "Document Name";
        }

        public void btnDocView_Click(object sender, RoutedEventArgs e)
        {
            if (formtype == "NEW")
            {

                ucDocs delobj = new ucDocs();
                Button clickedButton = (Button)sender;
                string s = clickedButton.Uid[0].ToString();
                string ucname = s + "label";
                for (int i = 0; i < lstpaths.Count; i++)
                {
                    if (lstpaths[i].FILETYPE == "OTF")
                    {
                        string[] str = lstpaths[i].FILENAME.Split('|');

                        if (ucname == str[2])
                        {

                            System.Diagnostics.Process.Start(lstpaths[i].FILEPATH);
                            return;
                        }
                    }
                }

                //    System.Diagnostics.Process.Start(fnlpath);
                //}
                //ucDocs delobj = new ucDocs();
                //string dpath;
                //Button clickedButton = (Button)sender;
                ////MessageBox.Show(clickedButton.Uid);

                //string s = clickedButton.Uid[0].ToString();
                //string ucname = s + "uc";
                //for (int i = 0; i < lstpaths.Count; i++)
                //{

                //    for (int j = 0; j < grdDocs.Children.Count; j++)
                //    {
                //        if (grdDocs.Children[j].Uid == ucname)
                //        {

                //            dpath = lstpaths[j].FILEPATH;
                //            System.Diagnostics.Process.Start(dpath);
                //            return;
                //        }
                //    }

                //}
            }
            if (formtype == "EDIT")
            {
                ucDocs delobj = new ucDocs();
                string dpath;
                Button clickedButton = (Button)sender;
                //MessageBox.Show(clickedButton.Uid);
                if (clickedButton.Uid[1].ToString() == "d")
                {
                    string s = clickedButton.Uid[0].ToString();
                    string ucname = s + "uc";
                    for (int i = 0; i < docDBPaths.Count; i++)
                    {
                        if (docDBPaths[i].DOCTYPE == "OTH" && docDBPaths[i].LBL == s)
                        {
                            for (int j = 0; j < grdDocs.Children.Count; j++)
                            {
                                if (grdDocs.Children[j].Uid == ucname)
                                {
                                    //string path = getPathofFile();
                                    dpath = docDBPaths[i].DOCPATH;
                                    //path += "\\" + dpath;
                                    try{
                                        System.Diagnostics.Process.Start(dpath);
                                    }
                                    catch (Exception ex) { }
                                    return;
                                }
                            }
                        }
                    }
                }
                else
                {
                    string s = clickedButton.Uid[0].ToString();
                    string ucname = s + "uc";
                    for (int i = 0; i < docDBUpdatePaths.Count; i++)
                    {
                        if (docDBUpdatePaths[i].DOCTYPE == "OTH" && docDBUpdatePaths[i].LBL == s)
                        {
                            for (int j = 0; j < grdDocs.Children.Count; j++)
                            {
                                if (grdDocs.Children[j].Uid == ucname)
                                {

                                    dpath = docDBUpdatePaths[i].DOCPATH;
                                    System.Diagnostics.Process.Start(dpath);
                                    return;
                                }
                            }
                        }

                    }
                }
            }

        }

        public void btnDocRemove_Click(object sender, RoutedEventArgs e)
        {
            if (formtype == "NEW")
            {
                ucDocs delobj = new ucDocs();
                string dpath;
                Button clickedButton = (Button)sender;
                //  MessageBox.Show(clickedButton.Uid);
                string s = clickedButton.Uid[0].ToString();
                string ucname = s + "uc";
                string lname = s + "label";
                for (int j = 0; j < grdDocs.Children.Count; j++)
                {
                    if (grdDocs.Children[j].Uid == ucname)
                    {
                        for (int i = 0; i < lstpaths.Count; i++)
                        {
                            if (lstpaths[i].FILETYPE == "OTF")
                            {
                                string[] splitName = lstpaths[i].FILENAME.Split('|');
                                if (lname == splitName[2])
                                {
                                    grdDocs.Children.RemoveAt(j);
                                    File.Delete(lstpaths[i].FILEPATH);
                                    lstpaths.RemoveAt(i);
                                }
                            }
                        }
                    }

                }
            }
            else if (formtype == "EDIT")
            {
                //lunch
                ucDocs delobj = new ucDocs();
                string dpath;
                Button clickedButton = (Button)sender;
                //  MessageBox.Show(clickedButton.Uid);
                //if (clickedButton.Uid[1].ToString() == "d")
                //{
                //    string s = clickedButton.Uid[0].ToString();
                //    string ucname = s + "uc";
                //    string lname = s + "label";
                //    grdDocs.Children.RemoveAt(Int32.Parse(s));
                //}
                //else
                //{
                if (clickedButton.Uid[1].ToString() == "d")
                {
                    string s = clickedButton.Uid[0].ToString();
                    string ucname = s + "uc";
                    for (int i = 0; i < docDBPaths.Count; i++)
                    {
                        if (docDBPaths[i].LBL == s)
                        {
                            for (int j = 0; j < grdDocs.Children.Count; j++)
                            {
                                if (grdDocs.Children[j].Uid == ucname)
                                {
                                    //string path = getPathofFile();
                                    //dpath = docDBPaths[i].DOCPATH;
                                    grdDocs.Children.RemoveAt(j);
                                    //path += "\\" + docDBPaths[i].DOCPATH;
                                    docDBRemovePaths.Add(new DocPaths(docDBPaths[i].DOCID, docDBPaths[i].DOCNAME, docDBPaths[i].DOCPATH, "OTH", s));
                                    docDBPaths.RemoveAt(i);

                                }
                            }
                        }
                    }
                }
                else
                {
                    string s = clickedButton.Uid[0].ToString();
                    string ucname = s + "uc";
                    for (int i = 0; i < docDBUpdatePaths.Count; i++)
                    {
                        if (docDBUpdatePaths[i].DOCTYPE == "OTH")
                        {
                            for (int j = 0; j < grdDocs.Children.Count; j++)
                            {
                                if (grdDocs.Children[j].Uid == ucname)
                                {
                                    dpath = docDBUpdatePaths[i].DOCPATH;
                                    File.Delete(dpath);
                                    grdDocs.Children.RemoveAt(j);
                                    docDBUpdatePaths.RemoveAt(i);
                                    //System.Diagnostics.Process.Start(dpath);
                                    //return;
                                }
                            }
                        }


                    }
                }
            }
        }

        private void btnNext_Click(object sender, RoutedEventArgs e)
        {

        }

        #endregion

        #region  Fill Other Documents IN EDIT mode

        public void Fillotherdocs()
        {

            //int cnt = 0;
            //rowCount4Docs = 0;
            for (int i = 0; i < docDBPaths.Count; i++)
            {
                if (docDBPaths[i].DOCTYPE != "ID" && docDBPaths[i].DOCTYPE != "NP")
                {
                    scrollViewer1.Visibility = Visibility.Visible;
                    RowDefinition rd = new RowDefinition();
                    rd.Name = "row1";
                    grdDocs.RowDefinitions.Add(rd);
                    ucDocs ucObj = new ucDocs();
                    Grid.SetRow(ucObj, rowCount4Docs++);

                    string namev = cnt + "dview";
                    string namer = cnt + "dbremove";
                    string namel = cnt + "label";
                    ucObj.Uid = cnt + "uc";
                    ucObj.btnDocView.Uid = namev;
                    ucObj.btnDocRemove.Uid = namer;
                    ucObj.lblDocName.Uid = namel;
                    docDBPaths[i].LBL = cnt.ToString();
                    cnt++;
                    ucObj.lblDocName.Content = docDBPaths[i].DOCNAME;
                    string[] x = docDBPaths[i].DOCPATH.Split('/');
                    ucObj.lblFname.Content = SplitByLength(x[x.Length - 1], 20);


                    //fnlpath = path;
                    DocDictionary.Add(cnt, txtDocName.Text);
                    ucObj.btnDocView.Click += new RoutedEventHandler(btnDocView_Click);
                    ucObj.btnDocRemove.Click += new RoutedEventHandler(btnDocRemove_Click);
                    grdDocs.Children.Add(ucObj);
                }
            }
        }

        #endregion

        private void photoUploadNEW(string path)
        {
            OpenFileDialog fileDIalog = new OpenFileDialog();

            fileDIalog.Filter = "All files (*.*)|*.*";

            fileDIalog.AddExtension = true;

            if (fileDIalog.ShowDialog() == true)
            {
                FileName = fileDIalog.FileName;
                string[] st = FileName.Split('\\');
                string[] spt = st[st.Length - 1].ToString().Split('.');
              
                string newPath = path;
                System.IO.Directory.CreateDirectory(newPath);

                path += "\\Photo"+"."+spt[spt.Length-1].ToString();
                fnlPhotoup = path;
                lstpaths.Add(new filePaths("Photo", path, "Photo"));
                try
                {
                    if (!File.Exists(path))
                    {
                        File.Copy(FileName, path);
                        BitmapImage src = new BitmapImage();
                        src.BeginInit();
                        src.UriSource = new Uri(path.Trim(), UriKind.Relative);
                        src.CacheOption = BitmapCacheOption.OnLoad;
                        src.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                        src.EndInit();
                        imgPhoto.Visibility = Visibility.Visible;
                        imgPhoto.Source = src;
                        btnCapture.Content = "Remove";
                        btnUpload.Content = "View Photo";
                    }
                    else
                    {
                        MessageBox.Show("photo Already Uploaded");
                        BitmapImage src = new BitmapImage();
                        src.BeginInit();
                        src.UriSource = new Uri(path.Trim(), UriKind.Relative);
                        src.CacheOption = BitmapCacheOption.OnLoad;
                        src.EndInit();
                        imgPhoto.Visibility = Visibility.Visible;
                        imgPhoto.Source = src;
                        btnCapture.Content = "Remove";
                        btnUpload.Content = "View Photo";
                    }
                }
                catch(Exception ex)
                { 
                }
                
                btnUpload.Content = Mode.ViewPhoto.ToString();
            }
        }

        private void familyPhotoUploadNEW(string path)
        {
            OpenFileDialog fileDIalog = new OpenFileDialog();
            fileDIalog.Filter = "All files (*.*)|*.*";
            fileDIalog.AddExtension = true;
            if (fileDIalog.ShowDialog() == true)
            {
                FileName = fileDIalog.FileName;
                string[] st = FileName.Split('\\');
                string[] spt = st[st.Length - 1].ToString().Split('.');
                string newPath = path; //System.IO.Path.Combine(path, Eid);
                System.IO.Directory.CreateDirectory(newPath);

                String[] PhotoName;
                PhotoName = FileName.Split('\\');
                path += "\\FamilyPhoto" + "." + spt[spt.Length - 1].ToString();

                fnlFPhotoup = path;
                lstpaths.Add(new filePaths("FamilyPhoto", path, "FamilyPhoto"));
                try
                {
                    if (!File.Exists(path))
                    {
                        File.Copy(FileName, path);
                        btnUpLoadFamily.Content = "View Photo";
                    }
                    else
                    {
                        MessageBox.Show("Photo Already Uploaded", "Photo", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    }
                    BitmapImage src = new BitmapImage();
                    src.BeginInit();
                    src.UriSource = new Uri(path.Trim(), UriKind.Relative);
                    src.CacheOption = BitmapCacheOption.OnLoad;

                    src.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                    src.EndInit();
                    imgFamilyPhoto.Source = src;
                    imgFamilyPhoto.Visibility = Visibility.Visible;
                    btnUpLoadFamily.Content = "View Photo";
                }
                catch(Exception ex)
                { }
                return;
            }
        }
        //collections
        public class filePaths
        {
            string filename;
            string filepath;
            string filetype;
            string index;
            public filePaths(string name, string path, string type)
            {
                this.filename = name;
                this.filepath = path;
                this.filetype = type;
            }
            public string FILENAME
            {
                set
                {
                    this.filename = value;
                }
                get
                {
                    return filename;
                }
            }
            public string FILETYPE
            {
                set
                {
                    this.filetype = value;
                }
                get
                {
                    return filetype;
                }
            }
            public string FILEPATH
            {
                set
                {
                    this.filepath = value;
                }
                get
                {
                    return filepath;
                }
            }
        }

        //other documents collection
        public class DocPaths
        {
            int docid;
            string docname;
            string docpath;
            string doctype;
            string lbl;
            public DocPaths(int id, string name, string path, string type, string lbl)
            {
                this.docid = id;
                this.docname = name;
                this.docpath = path;
                this.doctype = type;
                this.lbl = lbl;
            }
            public int DOCID
            {
                set
                {
                    this.docid = value;
                }
                get
                {
                    return docid;
                }
            }
            public string DOCTYPE
            {
                set
                {
                    this.doctype = value;
                }
                get
                {
                    return doctype;
                }
            }
            public string LBL
            {
                set
                {
                    this.lbl = value;
                }
                get
                {
                    return lbl;
                }
            }
            public string DOCNAME
            {
                set
                {
                    this.docname = value;
                }
                get
                {
                    return docname;
                }
            }
            public string DOCPATH
            {
                set
                {
                    this.docpath = value;
                }
                get
                {
                    return docpath;
                }
            }
        }

        private void grdDocsTelrik_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangeEventArgs e)
        {

        }

        private void cbMaritalStatus_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbSelect == 1)
            {
                txtSpouseName.IsEnabled = false;
                txtSpouseName.Text = "";
                cbSelect = 0;
            }


            if (((ComboBoxItem)cbMaritalStatus.SelectedItem).Content.ToString() == "Single" || ((ComboBoxItem)cbMaritalStatus.SelectedItem).Content.ToString() == "Widow")//||((ComboBoxItem)cbMaritalStatus.SelectedItem).Content.ToString() == "--SELECT--")
            {
                txtSpouseName.IsEnabled = false;
                txtSpouseName.Text = "";
            }
            else if (((ComboBoxItem)cbMaritalStatus.SelectedItem).Content.ToString() == "Married")
            {
                txtSpouseName.IsEnabled = true;
                cbSelect = 1;
            }
            
            
        }

        //split String
        public string SplitByLength(string s, int count)
        {
            if (count > s.Length)
            {
                return s;
            }

            string[] dotSplit = s.Split('.');
            string splittedString = "";
            for (int i = 0; i < count && i < s.Length; i++)
            {
                splittedString += s[i];
            }

            if (s.Length - 3 > count)
            {
                return splittedString + "." + dotSplit[dotSplit.Length - 1];
            }
            return splittedString;
        }

        private void datePick_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            //DateTime today = DateTime.Now;
            //DateTime Dob = (DateTime)datePick.SelectedDate;
            //string age;
            //age = ((today - Dob).Days).ToString();
            //if (Int32.Parse(age) < 6570)
            //{
            //    MessageBox.Show("Age Cannot Be Less than 18");
            //    return;
            //}
        }

        //Validations
        #region validations
        public bool Validation()
        {
            lblName.Foreground = System.Windows.Media.Brushes.DimGray;
            lblLName.Foreground = System.Windows.Media.Brushes.DimGray;
            lblFName.Foreground = System.Windows.Media.Brushes.DimGray;
            lblDOB.Foreground = System.Windows.Media.Brushes.DimGray;
            lblSpouseName.Foreground = System.Windows.Media.Brushes.DimGray;


            if (txtFirstName.Text == "")
            {
                lblName.Foreground = System.Windows.Media.Brushes.Red;
                MessageBox.Show("First Name is mandatory", "FirstName", MessageBoxButton.OK, MessageBoxImage.Warning);
                //lblNameVald.Content = "*";
                txtFirstName.Focus();
                
                return false;
            }
            else
            {
                //  lblNameVald.Content = "";
                lblName.Foreground = System.Windows.Media.Brushes.DimGray;
            }
            Regex nameRE = new Regex(@"^[a-zA-Z\s]+$");
            if (!nameRE.IsMatch(txtFirstName.Text) && txtFirstName.Text != "")
            {
                lblName.Foreground = System.Windows.Media.Brushes.Red;
                MessageBox.Show("Enter First Name Correctly", "FirstName", MessageBoxButton.OK, MessageBoxImage.Warning);
                txtFirstName.Focus();
                
                return false;
            }
            else
            {
                //  lblNameVald.Content = "";
                lblName.Foreground = System.Windows.Media.Brushes.DimGray;
            }
            if (!nameRE.IsMatch(txtLastName.Text) && txtLastName.Text != "")
            {
                lblLName.Foreground = System.Windows.Media.Brushes.Red;
                MessageBox.Show("Enter Last Name Correctly", "LastName", MessageBoxButton.OK, MessageBoxImage.Warning);
                txtFirstName.Focus();
                return false;
            }
            else
            {
                lblLName.Foreground = System.Windows.Media.Brushes.DimGray;
            }
            
            if (datePick.Text == "")
            {
                MessageBox.Show("Date of birth is mandatory", "Date Of Birth", MessageBoxButton.OK, MessageBoxImage.Warning);
                datePick.Focus();
                return false;
            }
            DateTime today = DateTime.Now;
            DateTime Dob = (DateTime)datePick.SelectedDate;
            string age;
            age = ((today - Dob).Days).ToString();
            if (Int32.Parse(age) < 6570)
            {
                MessageBox.Show("Age Cannot Be Less than 18", "Date Of Birth", MessageBoxButton.OK, MessageBoxImage.Warning);
                //lblDobVald.Content = "*";
                lblDOB.Foreground = System.Windows.Media.Brushes.Red;
                return false;
            }
            else
            {
                lblDOB.Foreground = System.Windows.Media.Brushes.DimGray;
            }
            if (txtFatherName.Text == "")
            {
                lblFName.Foreground = System.Windows.Media.Brushes.Red;
                MessageBox.Show("Father Name Can't be Empty", "FatherName", MessageBoxButton.OK, MessageBoxImage.Warning);
                txtFatherName.Focus();
                // lblFatherNameVald.Content = "*";
                return false;
            }
            else
            {
                lblFName.Foreground = System.Windows.Media.Brushes.DimGray;
                //  lblFatherNameVald.Content = "";
            }
            if (!nameRE.IsMatch(txtFatherName.Text) && txtFatherName.Text != "")
            {
                lblFName.Foreground = System.Windows.Media.Brushes.Red;
                MessageBox.Show("Enter Father Name Correctly", "FatherName", MessageBoxButton.OK, MessageBoxImage.Warning);
                txtFatherName.Focus();
                return false;
            }
            else
            {
                lblFName.Foreground = System.Windows.Media.Brushes.DimGray;
                //  lblFatherNameVald.Content = "";
            }
            if (cbMaritalStatus.SelectedIndex == 0)
            {
                MessageBox.Show("Select Marital Status", "Marital Status", MessageBoxButton.OK, MessageBoxImage.Warning);
                cbMaritalStatus.Focus();
                lblMaritalStatus.Foreground = System.Windows.Media.Brushes.Red;
                //lblMStatusVald.Content = "*";
                return false;
            }
            else
            {
                lblMaritalStatus.Foreground = System.Windows.Media.Brushes.DimGray;
                //lblMStatusVald.Content = "";
            }
            if (cbMaritalStatus.SelectedIndex == 2 && txtSpouseName.Text == "")
            {
                lblSpouseName.Foreground = System.Windows.Media.Brushes.Red;
                MessageBox.Show("Spouse Name is Mandatory", "Spouse Name", MessageBoxButton.OK, MessageBoxImage.Warning);
                txtSpouseName.Focus();
                //lblSpouseNameVald.Content = "*";
                return false;
            }
            else
            {
                lblSpouseName.Foreground = System.Windows.Media.Brushes.DimGray;
                lblSpouseNameVald.Content = "";
            }
            if (!nameRE.IsMatch(txtSpouseName.Text) && txtSpouseName.Text != "" && cbMaritalStatus.SelectedIndex == 2)
            {
                lblSpouseName.Foreground = System.Windows.Media.Brushes.Red;
                MessageBox.Show("Enter Spouse Name Correctly", "Spouse Name", MessageBoxButton.OK, MessageBoxImage.Warning);
                txtSpouseName.Focus();
                return false;
            }
            else
            {
                lblSpouseName.Foreground = System.Windows.Media.Brushes.DimGray;
            }

            if (txtFirstName.Text != "" && txtFatherName.Text != "" && datePick.Text != "")
            {

                return true;
            }
            return true;

        }
        public void RegularExpValidations()
        {

        }

        #endregion

        //Testing Code
        //#region Testing code
        //public class TestCase
        //{
        //    public int TestId;
        //    public string TestCaseDesc;
        //    public bool IsPass;
        //}
        //private void btnAtTest_Click(object sender, RoutedEventArgs e)
        //{
        //    tstCaseObj.Clear();
        //    ValidateTest();
        //    string TestCaseLogSuccess = "";
        //    string TestCaseLogFail = "";
        //    foreach (TestCase t in tstCaseObj)
        //    {
        //        if (t.IsPass)
        //        {
        //            TestCaseLogSuccess += "Test Case ID: " + t.TestId + ", Test Case: " + t.TestCaseDesc + ", Is Pass: " + t.IsPass + "\n";
        //        }
        //        else
        //        {
        //            TestCaseLogFail += "Test Case ID: " + t.TestId + ", Test Case: " + t.TestCaseDesc + ", Is Pass: " + t.IsPass + "\n";
        //        }

        //    }
        //    MessageBox.Show("Testy Case Pass - Log \n\n" + TestCaseLogSuccess + "\n\nTest Case Fail\n\n" + TestCaseLogFail, "Test Case Log", MessageBoxButton.OK, MessageBoxImage.Information);
        //}

        //private void ValidateTest()
        //{

        //    Regex nameRE = new Regex(@"^[a-zA-Z\s]+$");
        //    int seed = 1;
        //    TestCase TestObj;
        //    TestObj = new TestCase();
        //    testTextbox(TestObj, seed, "First Name is Mandatory", (txtFirstName.Text != "") ? true : false);
        //    TestObj = new TestCase();
        //    testTextbox(TestObj, seed, "First Name should be in correct Format if Available", (txtFirstName.Text != "" && !nameRE.IsMatch(txtFirstName.Text)) ? false : true);
        //    TestObj = new TestCase();
        //    testTextbox(TestObj, seed, "Last Name should be in correct Format if Available", (txtLastName.Text != "" && !nameRE.IsMatch(txtLastName.Text)) ? false : true);
        //    TestObj = new TestCase();
        //    TestObj.TestId = seed++;
        //    TestObj.TestCaseDesc = "Date of Birth Should be Greater than 18";
        //    DateTime today = DateTime.Now;
        //    DateTime Dob = (DateTime)datePick.SelectedDate;
        //    string age;
        //    age = ((today - Dob).Days).ToString();
        //    if (Int32.Parse(age) > 6570)
        //    {
        //        TestObj.IsPass = true;
        //        tstCaseObj.Add(TestObj);
        //    }
        //    else
        //    {
        //        TestObj.IsPass = false;
        //        tstCaseObj.Add(TestObj);
        //    }

        //    TestObj = new TestCase();
        //    testTextbox(TestObj, seed, "Father Name is Mandatory", (txtFatherName.Text != "") ? true : false);
        //    TestObj = new TestCase();
        //    testTextbox(TestObj, seed, "Father Name should be in correct Format if Available", (txtFatherName.Text != "" && !nameRE.IsMatch(txtFatherName.Text)) ? false : true);
        //    TestObj = new TestCase();
        //    testTextbox(TestObj, seed, "Marital Status is Mandatory", (cbMaritalStatus.SelectedIndex != 0) ? true : false);
        //    TestObj = new TestCase();
        //    testTextbox(TestObj, seed, "Spouse Name is Mandatory", (txtSpouseName.Text == "" && cbMaritalStatus.SelectedIndex == 2) ? false : true);
        //    TestObj = new TestCase();
        //    testTextbox(TestObj, seed, "Spouse Name should be in correct Format if Available", (txtSpouseName.Text != "" && !nameRE.IsMatch(txtSpouseName.Text)) ? false : true);




        //}
        //private void testTextbox(TestCase TestObj, int seed, string Desc, bool test)
        //{
        //    TestObj.TestId = seed++;
        //    TestObj.TestCaseDesc = Desc;
        //    if (test)
        //    {
        //        TestObj.IsPass = true;
        //        tstCaseObj.Add(TestObj);
        //    }

        //    else
        //    {
        //        TestObj.IsPass = false;
        //        tstCaseObj.Add(TestObj);
        //    }
        //}

        //#endregion

        private void txtDocName_TextInput(object sender, TextCompositionEventArgs e)
        {
            txtDocName.Text = "";
        }

        private void txtDocName_SelectionChanged(object sender, RoutedEventArgs e)
        {
            //if (txtDocName.ToolTip != null)
            //{
            //    txtDocName.Text = "";
            //}
            //txtDocName.ToolTip. == "tt";
        }

        private void txtDocName_GotFocus(object sender, RoutedEventArgs e)
        {
            //if (clickCount>0)
            {
                txtDocName.Text = "";
            }

            clickCount++;
        }

        private void txtDocName_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void rdoMale_Checked(object sender, RoutedEventArgs e)
        {

        }
        #region clear fields
        public void ClearFieldsPersonal()
        {
            rowCount4Docs = 0;
            viewpath1 = ""; fnlpath = "";
            cnt = 0;
            reft = 0; viewpathid = ""; viewpathNA = "";
            s = "";
            Isactive = 0; Eid = "";
            formtype = "";
            etype = "";

            tstCaseObj.Clear();

            empmode = "";
            flag = 0;
            IDProof = ""; NTProof = ""; OtherDoc1 = ""; Photo = ""; FamilyPhoto = ""; idproof = ""; ntvproof = "";

            adt.Clear();
            lstpaths.Clear(); othersDocs.Clear(); lstotherpaths.Clear(); lstDbPaths.Clear(); lstRemovePaths.Clear(); Updatedlst.Clear(); docDBPaths.Clear();
            docDBRemovePaths.Clear(); docDBUpdatePaths.Clear(); DocDictionary.Clear();
            clickCount = 0;
            grdDocuments.Children.Clear();
        }
        #endregion

        private void ftpTest_Click(object sender, RoutedEventArgs e)
        {
            string ftpPath = "ftp://118.139.163.181/" + "Documents" + "/" + "Employees" + "/" + empmode + "/" + Eid + "/";

            //FtpWebRequest request = (FtpWebRequest)WebRequest.Create(photopath);
            //request.Method = WebRequestMethods.Ftp.GetFileSize;

            //FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            //MessageBox.Show(response.ToString());

            if (CheckFTPFile("Photo1.jpg", ftpPath)) MessageBox.Show("Exists"); else MessageBox.Show("doesn't exists");

        }
        public bool CheckFTPFile(string fileName, string strFTPPath)
        {
            FtpWebRequest reqFTP;

            // dirName = name of the directory to create.

            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(strFTPPath));
            reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
            reqFTP.UseBinary = true;
            FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
            StreamReader ftpStream = new StreamReader(response.GetResponseStream());

            List<string> files = new List<string>();
            string line = ftpStream.ReadLine();
            while (line != null)
            {
                files.Add(line);
                line = ftpStream.ReadLine();
            }

            ftpStream.Close();
            response.Close();

            return files.Contains(fileName);
        }

    }
    #endregion

    //Enum class for button text
    public enum Mode
    {
        Capture,
        Loading,
        TakePhoto,
        Remove,
        Upload,
        ViewPhoto
    }
}